package com.yuanxiong.getweather.ui;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.yuanxiong.getweather.R;
import com.yuanxiong.getweather.gson.ChartInfo;
import com.yuanxiong.getweather.gson.WeatherInfo;
import com.yuanxiong.getweather.util.HttpUtil;
import com.yuanxiong.getweather.util.Utility;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import lecho.lib.hellocharts.view.LineChartView;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class WeatherActivity extends AppCompatActivity {
    private static final String TAG = "WeatherActivity";

    public static final String KEY = "xxxxxxxx";//聚合数据-"天气预报"api
    private static final String PREFIX_URL = "http://apis.juhe.cn/simpleWeather/query?city=";
    private static final String SUFFIX_URL = "&key=" + KEY;


    private TextView city;
    private TextView updateTime;

    private TextView realtimeTemp;
    private TextView realtimeInfo;
    private TextView realtimeHumidity;
    private TextView realtimeDirect;
    private TextView realtimePower;
    private TextView realtimeAQI;

    private SwipeRefreshLayout mSwipeRefresh;

    private LineChartView lineChart;

    private Context mContext;
    private String currentCity = "苏州";

    public static final int REQUEST_CODE = 10011;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_weather);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        mContext = this;
        initView();
        mSwipeRefresh.setRefreshing(true);
        requestWeatherInfo(currentCity);
    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    private void initView() {

        city = findViewById(R.id.city_name);
        city.setOnClickListener(cityListener);

        updateTime = findViewById(R.id.update_time);

        realtimeTemp = findViewById(R.id.realtime_temperature);
        realtimeInfo = findViewById(R.id.realtime_info);
        realtimeHumidity = findViewById(R.id.realtime_humidity);
        realtimeDirect = findViewById(R.id.realtime_direct);
        realtimePower = findViewById(R.id.realtime_power);
        realtimeAQI = findViewById(R.id.realtime_aqi);

        mSwipeRefresh = findViewById(R.id.swipe_refresh);
        mSwipeRefresh.setOnRefreshListener(onRefreshListener);

        lineChart = (LineChartView) findViewById(R.id.chart);

    }

    SwipeRefreshLayout.OnRefreshListener onRefreshListener = new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            Log.d(TAG, "onRefresh: ");
            requestWeatherInfo(currentCity);

        }
    };

    View.OnClickListener cityListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(mContext, AreaActivity.class);
            startActivityForResult(intent, REQUEST_CODE);
        }
    };

    private void refreshUI(WeatherInfo weatherInfo) {
        city.setText(weatherInfo.getResult().getCity());

        realtimeTemp.setText(weatherInfo.getResult().getRealtime().getTemperature() + "°");
        realtimeInfo.setText(weatherInfo.getResult().getRealtime().getInfo());
        realtimeHumidity.setText("湿度: " + weatherInfo.getResult().getRealtime().getHumidity() + "%");
        realtimeDirect.setText(weatherInfo.getResult().getRealtime().getDirect());
        realtimePower.setText(weatherInfo.getResult().getRealtime().getPower());
        realtimeAQI.setText("AQI: " + weatherInfo.getResult().getRealtime().getAqi());
        Log.d(TAG, "refreshUI: size= " + weatherInfo.getResult().getFuture().size());

        Utility.setChartViewData(getFutureTmpHigh(weatherInfo.getResult().getFuture()), lineChart);

    }

    private List<ChartInfo> getFutureTmpHigh(List<WeatherInfo.ResultBean.FutureBean> futureList) {
        List<ChartInfo> list = new ArrayList<>();


        for (int i = 0; i < futureList.size(); i++) {
            ChartInfo chartInfo = new ChartInfo();
            chartInfo.setHighTmp(Utility.getHighNum(futureList.get(i).getTemperature()));
            chartInfo.setDate(Utility.getMonthDate(futureList.get(i).getDate()));
            list.add(chartInfo);
        }
        return list;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == REQUEST_CODE && data != null) {
            String result = data.getStringExtra("result");
            Log.d(TAG, "onActivityResult: " + result);
            currentCity = result;
            mSwipeRefresh.setRefreshing(true);
            requestWeatherInfo(currentCity);
        }
    }

    public void requestWeatherInfo(String cityName) {

        /**
         * 请求示例: "http://apis.juhe.cn/simpleWeather/query?city=%E8%8B%8F%E5%B7%9E&key="
         */

        String weatherUrlByCity = PREFIX_URL + cityName + SUFFIX_URL;
        Log.d(TAG, "requestWeatherInfo: weatherUrlByCity= " + weatherUrlByCity);
        HttpUtil.sendOKHttpRequest(weatherUrlByCity, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                mSwipeRefresh.setRefreshing(false);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String responseText = response.body().string();
                Log.d(TAG, "onResponse: " + responseText);
                final WeatherInfo weatherInfo = Utility.handleWeatherResponse(responseText);

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (weatherInfo != null) {
                            refreshUI(weatherInfo);
                            Log.d(TAG, "onResponse: reason= " + weatherInfo.getReason()
                                    + "\ntemperature=" + weatherInfo.getResult().getRealtime().getTemperature());
                        }

                        mSwipeRefresh.setRefreshing(false);
                    }
                });

            }
        });
    }
}
